Resumen

Row

Cantidad de proyectos

160795

Total presupuesto inicial

64797.56

Total presupuesto vigente

83055.65

Total ejecutado

49224.46

% ejecutado

Row

Presupuestado vs Ejecutado

Row

Cantidad de proyectos por departamento

Porcentaje de proyectos por departamento

Sector

Row

Número de Proyectos por tipo de Sector

% ejecución por tipo de Sector

Row

Barras

Área

Tabla

Departamento

Row

Número de Proyectos por Departamento

% ejecución por departamento

Row

Barras

Área

Tabla

Región

Row

Número de Proyectos por región

% ejecución por Región

Row

Barras

Densidad

Tabla

Tipo de entidad

Row

Número de Proyectos por tipo de entidad

% ejecución por tipo de entidad

Row

Barras

Densidad

Tabla

Financiamiento

Row

Número de Proyectos por financiamiento

% ejecución por financiamiento

Row

Barras

Densidad

Tabla

Gráfico Dinámico

Gráfico por departamentos de cantidad de proyectos con filtro por año

Informe

---
title: "Inversión pública 2006-2022"
author: "Ada Cueto - Alexander Sucre"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: fill
    source_code: embed
    theme:
      version: 4
      base_font:
        google: Sen
      code_font:
        google: JetBrains Mono
      bootswatch: darkly
---

```{r setup, include=FALSE}
rm(list = ls())
library("flexdashboard")
pacman::p_load(
  tidyverse,
  crosstalk,
  sparklyr,
  readxl,
  dplyr,
  ggplot2,
  GGally,
  ggthemes,
  plotly,
  DataExplorer,
  textshape,
  reticulate,
  knitr,
  DT
)
sc <- spark_connect(master = "local")
proy <- spark_read_csv(sc, name = "proyecto", path = "../_data/Proyectos.csv",memory = F)
proy <- proy %>% 
  mutate(presup=ifelse(!is.na(presupuesto_vigente) & presupuesto_vigente > 0,presupuesto_vigente,Presupuesto_inicial))
```

# Resumen {data-icon="fa-home"}

Row
-----------------------------------------------------------------------

### Cantidad de proyectos {.value-box}

```{r}
tot_proy <- proy %>% count() %>% rename(total=n) %>% collect()
valueBox(tot_proy, icon = "fa-database",color = "info")
```

### Total presupuesto inicial {.value-box}

```{r}
tot_pres <- proy %>% summarise(total=round(sum(Presupuesto_inicial),2)) %>% collect()
valueBox(tot_pres, icon = "fa-dollar-sign",color = "primary")
```

### Total presupuesto vigente {.value-box}

```{r}
tot_vig <- proy %>% 
  summarize(total = round(sum(presup),2)) %>% collect()
valueBox(tot_vig, icon = "fa-chart-line",color = "danger")
```

### Total ejecutado {.value-box}

```{r}
tot_ejec <- proy %>% summarise(total=round(sum(presupuesto_ejecutado,na.rm = TRUE),2)) %>% collect()
valueBox(tot_ejec, icon = "fa-money-bill-alt",color = "success")
```

### % ejecutado 

```{r}
por_ejec <- round(tot_ejec/tot_vig*100)
gauge(por_ejec$total, min = 0, max = 100, symbol = "%",
      gaugeSectors(
        success = c(0,por_ejec$total)
      ))
```

Row
-----------------------------------------------------------------------

### Presupuestado vs Ejecutado

```{r}
gest <- proy %>% 
  select(gestion,inicial=Presupuesto_inicial,vigente=presup,ejecutado=presupuesto_ejecutado) %>% 
  group_by(gestion) %>% 
  summarise(inicial=sum(inicial),vigente=sum(vigente),ejecutado=sum(ejecutado)) %>% 
  arrange(gestion) %>% 
  collect()

fig <- plot_ly(gest, x = ~gestion, y = ~inicial, type = 'scatter', mode = 'lines', fill = 'tozeroy', name = 'Inicial',fillcolor = 'primary')
fig <- fig %>% add_trace(y = ~vigente, name = 'Vigente',fillcolor = 'danger')
fig <- fig %>% add_trace(y = ~ejecutado, name = 'Ejecutado',fillcolor = 'info')

fig <- fig %>% layout(
  xaxis = list(title = 'Gestión'),
  yaxis = list(title = 'Monto en millones de dolares'),
  title = 'Comparación de presupuesto inicial, vigente y ejecutado por gestión'
)

fig
```

Row
-----------------------------------------------------------------------

### Cantidad de proyectos por departamento

```{r}
dep_n <- proy %>% 
  count(depto) %>% 
  rename(Departamento=depto,Cantidad=n) %>% 
  collect()
datatable(dep_n,options = list(paging=FALSE,searching=FALSE,info=FALSE))
```

### Porcentaje de proyectos por departamento

```{r}
dep_p <- proy %>% 
  count(depto) %>% 
  mutate(porcentaje = n/sum(n)*100) %>% 
  select(Departamento=depto,Porcentaje=porcentaje) %>%  
  collect()
plot_ly(dep_p,labels=~Departamento,values=~Porcentaje,type = "pie") %>% 
  layout(title="Proyectos por departamento",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
```

# Sector {data-navmenu="Análisis" data-icon="fa-business-time"}

```{r}
sector_tipo <- proy %>% 
  group_by(gestion,tipo_sector) %>% 
  summarise(tot_proy = count(),presup=sum(presup,na.rm = TRUE),ejec=sum(presupuesto_ejecutado,na.rm = TRUE))
```

Row {data-height=350}
-----------------------------------------------------------------------

### Número de Proyectos por tipo de Sector

```{r}
num_proy <- sector_tipo %>% 
  group_by(tipo_sector) %>%
  summarise(Cantidad = sum(tot_proy)) %>% 
  collect()

proy_reg <- ggplot(num_proy, aes(x = tipo_sector, y = Cantidad, fill = tipo_sector)) +
  geom_bar(stat = "identity",position = "stack") +
  labs(title = "Proyectos por tipo de sector", x = "tipo_sector", y = "Cantidad") +
  coord_flip()+
  theme_classic()
ggplotly(proy_reg)

```


### % ejecución por tipo de Sector

```{r}
plot_ly(num_proy,labels=~tipo_sector,values=~Cantidad,type = "pie", hole=0.4 ) %>% 
  layout(title="Proyectos por tipo de sector",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

```

Row {data-height=650, .tabset .tabset-fade}
-----------------------------------------------------------------------

### Barras 

```{r}
barra_reg <- ggplot(sector_tipo, aes(x = gestion, y = ejec, fill = tipo_sector)) +
  geom_bar(stat = "identity", position = "stack") +
  labs(title = "Ejecución por tipo de sector y Gestión",
       x = "Gestión", y = "Ejecución") +
  theme_minimal()
ggplotly(barra_reg)
```

### Área 

```{r}
tendencia <- sector_tipo %>% 
  group_by(tipo_sector,gestion) %>% 
  summarise(presup = sum(presup),ejec = sum(ejec)) %>% 
  pivot_longer(cols = c(presup, ejec),
               names_to = "Tipo",
               values_to = "Valor") %>% 
  collect() %>%
  mutate(
    tipo_sector = as.factor(tipo_sector),
    gestion = as.numeric(gestion),
    Tipo = as.factor(Tipo),
    Valor = as.numeric(Valor)
  )

tx <- highlight_key(tendencia)

x <- filter_select("id", "-  Seleccione:", tx, ~tipo_sector, multiple = FALSE) 


tendencia_graf <- ggplot(tx, aes(x = gestion, y = Valor, color = Tipo, group = Tipo)) +
  geom_line() +
  labs(title = "Gráfico de Tendencias Presupuesto vs Ejecución",
       x = "Gestión",
       y = "Valor") +
  scale_color_manual(values = c("presup" = "blue", "ejec" = "red")) +  # Cambiar colores si deseas
  theme_minimal()

tendencia_grafP <- ggplotly(tendencia_graf) 
bscols(x,tendencia_grafP,widths = c(3, 9))
```

### Tabla 

```{r}
datatable(sector_tipo %>% collect())
```

# Departamento {data-navmenu="Análisis" data-icon="fa-city"}

```{r}
departamento <- proy %>% 
  group_by(gestion,depto) %>% 
  summarise(tot_proy = count(),presup=sum(presup,na.rm = TRUE),ejec=sum(presupuesto_ejecutado,na.rm = TRUE))
```

Row {data-height=350}
-----------------------------------------------------------------------

### Número de Proyectos por Departamento

```{r}
bar<-ggplot(data=dep_n, aes(x=Departamento, y=Cantidad, fill=Departamento))+
  geom_bar(stat = "identity")+
  coord_flip()

ggplotly(bar) %>% layout(showlegend = FALSE)

```


### % ejecución por departamento

```{r}
dep_pe <- departamento %>% 
  group_by(Departamento = depto) %>% 
  summarise(Porcentaje = round(sum(ejec)/sum(presup)*100),2) %>% 
  arrange(Departamento) %>% 
  collect()

plot_ly(dep_pe,labels=~Departamento,values=~Porcentaje,type = "pie" ) %>% 
  layout(title="% Ejecucion por Departamento",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
```

Row {data-height=650, .tabset .tabset-fade}
-----------------------------------------------------------------------

### Barras 

```{r}
dep_vs<-departamento %>%
  group_by(depto) %>% 
  summarise(Presupuestado = sum(presup),Ejecutado = sum(ejec)) %>% 
  arrange(depto) %>% 
  collect()

dep_vs1 <- pivot_longer(dep_vs, cols = c(Presupuestado, Ejecutado), names_to = "Tipo", values_to = "Monto")

bar_dep <- ggplot(dep_vs1, aes(x = depto, y = Monto, fill = Tipo))+
  geom_bar(stat = "identity",position = "dodge")+
  labs(title = "Presupuesto vs. Ejecución por Departamento", x = "Departamento", y = "Monto")+
  theme_minimal()+
  theme(axis.text = element_text(angle = 45,hjust = 1))
ggplotly(bar_dep)
```

### Área 

```{r}

tendencia <- departamento %>% 
  group_by(gestion,Departamento = depto) %>% 
  summarise(Presupuestado = sum(presup),Ejecutado = sum(ejec)) %>% 
  pivot_longer(cols = c(Presupuestado, Ejecutado),
               names_to = "Tipo",
               values_to = "Valor") %>% 
  collect() %>%
  mutate(
    Departamento = as.factor(Departamento),
    gestion = as.numeric(gestion),
    Tipo = as.factor(Tipo),
    Valor = as.numeric(Valor)
  )

tx <- highlight_key(tendencia)

x <- filter_select("id", "-  Seleccione:", tx, ~Departamento, multiple = FALSE) 


bar_dep <- plot_ly(tx, x = ~gestion, y = ~ Valor , type="bar" , mode="markers", fillcolor = ~ Tipo) 
bscols(x,bar_dep,widths = c(3, 9))
```

### Tabla 

```{r}
datatable(departamento %>% collect())
```

# Región {data-navmenu="Análisis" data-icon="fa-map-marked"}

```{r}
region_d <- proy %>% 
  group_by(gestion,region) %>% 
  summarise(tot_proy = count(),presup=sum(presup,na.rm = TRUE),ejec=sum(presupuesto_ejecutado,na.rm = TRUE))
```

Row {data-height=350}
-----------------------------------------------------------------------

### Número de Proyectos por región

```{r}
num_proy <- region_d %>% 
  group_by(region) %>%
  summarise(Cantidad = sum(tot_proy)) %>% 
  rename(Region = region) %>% 
  collect()

proy_reg <- ggplot(num_proy, aes(x = Region, y = Cantidad, fill = Region)) +
  geom_bar(stat = "identity",position = "stack") +
  labs(title = "Proyectos por region", x = "Region", y = "Cantidad") +
  coord_flip()+
  theme_classic()
ggplotly(proy_reg)

```


### % ejecución por Región

```{r}
plot_ly(num_proy,labels=~Region,values=~Cantidad,type = "pie", hole=0.4 ) %>% 
  layout(title="Proyectos por Región",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

```

Row {data-height=650, .tabset .tabset-fade}
-----------------------------------------------------------------------

### Barras 

```{r}
barra_reg <- ggplot(region_d, aes(x = gestion, y = presup + ejec, fill = region)) +
  geom_bar(stat = "identity", position = "stack") +
  labs(title = "Presupuesto y Ejecución por Región",
       x = "Gestión", y = "Ejecución") +
  theme_minimal()
ggplotly(barra_reg)
```

### Densidad 

```{r}
area_reg <- ggplot(region_d, aes(x = ejec)) +
  geom_density(aes(fill = gestion), alpha = 0.5) +
  labs(title = "Presupuesto y Ejecución por Región",
       x = "Ejecución") +
  theme_minimal()
ggplotly(area_reg)
```

### Tabla 

```{r}
datatable(region_d %>% collect())
```

# Tipo de entidad {data-navmenu="Análisis" data-icon="fa-suit-case"}

```{r}
tipo_entidad_r <- proy %>% 
  group_by(gestion,tipo_entidad) %>% 
  summarise(tot_proy = count(),presup=sum(presup,na.rm = TRUE),ejec=sum(presupuesto_ejecutado,na.rm = TRUE))
```

Row {data-height=350}
-----------------------------------------------------------------------

### Número de Proyectos por tipo de entidad 

```{r}
num_proy <- tipo_entidad_r %>% 
  group_by(tipo_entidad) %>%
  summarise(Cantidad = sum(tot_proy)) %>% 
  arrange(desc(Cantidad)) %>% 
  head(15) %>% 
  collect()

proy_reg <- ggplot(num_proy, aes(x = tipo_entidad, y = Cantidad, fill = tipo_entidad)) +
  geom_bar(stat = "identity",position = "stack") +
  labs(title = "Proyectos por tipo de entidad", x = "Tipo entidad", y = "Cantidad") +
  coord_flip()+
  theme_classic()
ggplotly(proy_reg) %>% layout(showlegend = FALSE)

```


### % ejecución por tipo de entidad

```{r}
num_proy_1 <- num_proy %>% head(10)
plot_ly(num_proy_1,labels=~tipo_entidad,values=~Cantidad,type = "pie", hole=0.4 ) %>% 
  layout(title="Proyectos por tipo de entidad",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

```

Row {data-height=650, .tabset .tabset-fade}
-----------------------------------------------------------------------

### Barras 

```{r}
barra_reg <- ggplot(tipo_entidad_r, aes(x = gestion, y = ejec, fill = tipo_entidad)) +
  geom_bar(stat = "identity", position = "stack") +
  labs(title = "Ejecución por tipo de entidad",
       x = "Gestión", y = "Ejecución") +
  theme_minimal()
ggplotly(barra_reg)
```

### Densidad 

```{r}
area_reg <- ggplot(tipo_entidad_r, aes(x = ejec)) +
  geom_density(aes(fill = tipo_entidad), alpha = 0.5) +
  labs(title = "Ejecución por tipo de entidad",
       x = "Ejecución") +
  theme_minimal()
ggplotly(area_reg)
```

### Tabla 

```{r}
datatable(tipo_entidad_r %>% collect())
```

# Financiamiento {data-navmenu="Análisis" data-icon="fa-money-bill-wave"}

```{r}
financiamiento <- proy %>% 
  group_by(gestion,tipo_financiamiento) %>% 
  summarise(tot_proy = count(),presup=sum(presup,na.rm = TRUE),ejec=sum(presupuesto_ejecutado,na.rm = TRUE))
```

Row {data-height=350}
-----------------------------------------------------------------------

### Número de Proyectos por financiamiento

```{r}

recurso <- proy %>% 
  group_by(tipo_recurso) %>% 
  summarise(tot_proy = count(),presup=sum(presup,na.rm = TRUE),ejec=sum(presupuesto_ejecutado,na.rm = TRUE)) %>% 
  collect()

fig <- plot_ly()
fig <- fig %>% 
  add_pie(data = recurso, labels = ~tipo_recurso, values = ~tot_proy, name = "Total", domain = list(x = c(0, 0.4), y = c(0.4, 1)))
fig <- fig %>% 
  add_pie(data = recurso, labels = ~tipo_recurso, values = ~presup, name = "Presupuestado", domain = list(x = c(0.6, 1), y = c(0.4, 1)))

fig <- fig %>% 
  add_pie(data = recurso, labels = ~tipo_recurso, values = ~ejec, name = "Ejecutado", domain = list(x = c(0.25, 0.75), y = c(0, 0.6)))

fig <- fig %>% layout(title = "Financiamiento por recurso interno o externo", showlegend = F,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

fig

num_proy <- financiamiento %>% 
  group_by(tipo_financiamiento) %>%
  summarise(Cantidad = sum(tot_proy)) %>% 
  collect()

proy_reg <- ggplot(num_proy, aes(x = tipo_financiamiento, y = Cantidad, fill = tipo_financiamiento)) +
  geom_bar(stat = "identity",position = "stack") +
  labs(title = "Proyectos por financiamiento", x = "Financiamiento", y = "Cantidad") +
  coord_flip()+
  theme_classic()
ggplotly(proy_reg)

```


### % ejecución por financiamiento

```{r}
plot_ly(num_proy,labels=~tipo_financiamiento,values=~Cantidad,type = "pie") %>% 
  layout(title="Proyectos por financiamiento",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

```

Row {data-height=650, .tabset .tabset-fade}
-----------------------------------------------------------------------

### Barras 

```{r}
barra_reg <- ggplot(financiamiento, aes(x = gestion, y = presup + ejec, fill = tipo_financiamiento)) +
  geom_bar(stat = "identity", position = "stack") +
  labs(title = "Presupuesto y Ejecución por financiamiento",
       x = "Gestión", y = "Ejecución") +
  theme_minimal()
ggplotly(barra_reg)
```

### Densidad 

```{r}
area_reg <- ggplot(financiamiento, aes(x = ejec)) +
  geom_density(aes(fill = tipo_financiamiento), alpha = 0.5) +
  labs(title = "Presupuesto y Ejecución por financiamiento",
       x = "Ejecución") +
  theme_minimal()
ggplotly(area_reg)
```

### Tabla 

```{r}
datatable(financiamiento %>% collect())
```

# Gráfico Dinámico

### Gráfico por departamentos de cantidad de proyectos con filtro por año

```{r}
tot_proy <- proy %>% count(gestion, depto) %>% rename(total=n) %>% collect()
tot_proy$depto <- as.factor(tot_proy$depto)
tot_proy$gestion <- as.numeric(tot_proy$gestion)
tot_proy$total <- as.numeric(tot_proy$total)

tx <- highlight_key(tot_proy)

x <- filter_select("id", "-  Seleccione:", tx, ~gestion, multiple = FALSE)
p <- plot_ly(tx, x = ~depto, y = ~ total , type="bar", fillcolor =  ~depto) # %>% add_markers() 
bscols(x,p,widths = c(3, 9))

```


# Informe {data-icon="fa-file-alt"}

```{r, out.width='100%', out.height="100%" }
include_graphics("Informe.pdf")
```